<?php

namespace app\api\model;

use think\Exception;
use think\Model;
use think\Session;
use think\Db;
use think\Cache;


class User extends Model
{

    private $token;
    protected $table = 'rbl_member';
    public $user_name = null;
    public $user_id = null;

    // 初始化
    public function initialize()
    {


    }


    /**
     * 支付
     * @param array $post
     * @return string
     * @throws BaseException
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function pay_gateway($post)
    {
        $username = !empty($post['username']) ? $post['username'] : '1';
        $password = !empty($post['password']) ? $post['password'] : '';
        //查询账号密码对不对
        $data = Db::name('company_select')->where(['phone' => $username])->where('deletetime', null)->find();
        if (!$data) {
            throw new Exception('当前商户不存在');
        }
        if ($data['password'] != $this->auth->getEncryptPassword($password, $data['salt'])) {
            throw new Exception('当前商户密码不正确');
        }
        if ($data['switch'] == 0) {
            throw new Exception('当前商户已关闭，请联系管理员');
        }
    }


    /**
     * 获取用户信息
     * @param $token
     * @return null|static
     * @throws \think\exception\DbException
     */
    public function getUsers($param)
    {
        $openId = Cache::get($param);
        if (!$openId) {
            echo json_encode(['code' => -1, 'msg' => '没有找到用户信息']);
            die;
        }
//        dump($openId);die;
        //查询详情
        $detail = Db::name('wxuser')
            ->where(function ($query) use ($openId) {
                $query->where('openid', $openId)
                    ->whereOr('mobile', $openId);
            })
            ->where('deletetime', null)
            ->find();
        return $detail;
    }

    /**
     * 用户手机号登录
     * @param array $post
     * @return string
     * @throws \app\api\model\BaseException
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function loginindex($post)
    {
        // 微信登录 获取session_key
        $mobile = $post['mobile'];
        //查询用户信息
        $data = Db::name('wxuser')
            ->where(['mobile' => $mobile])
            ->where('deletetime', null)
            ->find();
        if (!$data) {
//            $this->error('查无此用户');
            //注册
            $data_s['mobile']     = $mobile;
            $data_s['nickname']   = $mobile;
            $data_s['createtime'] = time();
            $parent_user_id       = isset($post['user_id']) ? $post['user_id'] : '';
            if ($parent_user_id) {
                $data_s['parent_user_id'] = $parent_user_id;
                //查询当前设置的一起拼优惠券
                $points_coupon = Db::name('points_coupon')->where(['is_share' => 1])->where('deletetime', null)->find();
                if ($points_coupon) {
                    $data_s['coupon_id'] = $points_coupon['id'];
                }
            }
            $user_id        = Db::name('wxuser')->insertGetId($data_s);
            $data['id']     = $user_id;
            $data['openid'] = '';
        }

        $user_id = $data['id'];
        $openid  = $data['openid'] ? $data['openid'] : $mobile;

        // 生成token (session3rd)

        // 记录缓存, 7天

        $this->token = $this->token($openid);
        // 记录缓存, 7天
        Cache::set($this->token, $openid, 86400 * 7);
        return $user_id;
    }

    /**
     * 用户登录
     * @param array $post
     * @return string
     * @throws \app\api\model\BaseException
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function login($post)
    {
        // 微信登录 获取session_key
        $openid = $this->wxlogin($post['code']);

        // 自动注册用户
        $refereeId      = isset($post['referee_id']) ? $post['referee_id'] : null;
        $userInfo       = isset($post['nickname']) ? htmlspecialchars_decode($post['nickname']) : null;
        $post['avatar'] = isset($post['avatar']) ? $post['avatar'] : '';
        $parent_user_id = isset($post['user_id']) ? $post['user_id'] : '';
        $user_id        = $this->register($openid, $userInfo, $refereeId, $post['avatar'], $parent_user_id);
        // 生成token (session3rd)

        // 记录缓存, 7天

        $this->token = $this->token($openid);
        // 记录缓存, 7天
        Cache::set($this->token, $openid, 86400 * 7);
        return $user_id;
    }

    /**
     * 微信登录,获取openid
     * @param $code
     * @return array|mixed
     * @throws \app\api\model\BaseException
     * @throws \think\exception\DbException
     */
    public function wxlogin($code)
    {
        // 获取当前小程序信息
        //获取用户openid
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . config('appid') . '&secret=' . config('secret') . '&js_code=' . $code . '&grant_type=authorization_code';
        //yourAppid为开发者appid.appSecret为开发者的appsecret,都可以从微信公众平台获取；
        $info = file_get_contents($url);//发送HTTPs请求并获取返回的数据，推荐使用curl
        $json = json_decode($info);     //对json数据解码
        $arr  = get_object_vars($json);
//        if (isset($arr[ 'errcode' ])) {
//            echo json_encode(['code' => -1, 'msg' => $arr[ 'errmsg' ]]);
//            die;
//        }

        $openid = $arr[ 'openid' ];

//        $openid = '123';
        return $openid;
    }

    public function wxphone($param, $User)
    {
        $accessToken = $this->AccessToken();
        // $c           = request_by_curl("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=$accessToken", json_encode(['code' => $param['code']]));
        $request_url  = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" . $accessToken;
        $request_data = [
            'code' => $param['code'],
        ];
        $resArr       = json_decode(https_request($request_url, $request_data, 'json'), true);

        if (empty($resArr)) {
            echo json_encode(['code' => -1, 'msg' => '获取用户电话失败']);
            die;
        }
        if (isset($resArr['errcode']) && $resArr['errcode'] !== 0) {
            echo json_encode(['code' => -1, 'msg' => $resArr['errmsg']]);
            die;
        }
        if (empty($resArr['phone_info'])) {
            echo json_encode(['code' => -1, 'msg' => '获取用户电话失败1']);
            die;
        }

        $phone = $User['mobile'];
        if (empty($User['mobile'])) {
            Db::name('wxuser')->where(['id' => $User['id']])->update(['mobile' => $resArr['phone_info']['phoneNumber']]);
        }
        if (empty($User['admin_id'])) {
            //查询是否有关联
            $admin = Db::name('admin')->where(['mobile' => $resArr['phone_info']['phoneNumber']])->find();
            if ($admin) {
                Db::name('wxuser')->where(['id' => $User['id']])->update(['admin_id' => $admin['id']]);
            }
        }
        return $resArr['phone_info']['phoneNumber'];

    }

    /**
     * 获取access_token
     */
    public function AccessToken($param = '')
    {
        $url  = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . config('appid') . "&secret=" . config('secret');
        $info = file_get_contents($url);//发送HTTPs请求并获取返回的数据，推荐使用curl
        $json = json_decode($info);     //对json数据解码
        $arr  = get_object_vars($json);
        if (isset($arr['errcode'])) {
            echo json_encode(['code' => -1, 'msg' => $arr['errmsg']]);
            die;
        }
//         dump($arr);die;
        return $arr['access_token'];
    }

    /**
     * 获取token
     * @return mixed
     */
    public function getToken()
    {
        // dump(123);die;
        return $this->token;
    }

    /**
     * 生成用户认证的token
     * @param $openid
     * @return string
     */
    public function token($openid)
    {
        $wxapp_id = '1';
        // 生成一个不会重复的随机字符串
        $guid = getGuidV4();
        // 当前时间戳 (精确到毫秒)
        $timeStamp = microtime(true);
        // 自定义一个盐
        $salt = 'token_salt';
        return md5("{$wxapp_id}_{$timeStamp}_{$openid}_{$guid}_{$salt}");
    }

    /**
     * 自动注册用户
     * @param     $open_id
     * @param     $data
     * @param int $refereeId
     * @return mixed
     * @throws \Exception
     * @throws \think\exception\DbException
     */
    public function register($open_id, $data, $refereeId = null, $img, $parent_user_id)
    {

        // 查询用户是否已存在
        $find = Db::name('wxuser')
            ->where(['openid' => $open_id])
            ->where('deletetime', null)
            ->find();
        Db::startTrans();
        try {
            // 保存/更新用户记录
            if ($find) {
//                Db::name('wxuser')->where(['openid' => $open_id])->update(['nickname' => $data, 'avatar' => $img]);
                $user_id = $find['id'];
            } else {
                $data_s['openid']     = $open_id;
                $data_s['nickname']   = $data;
                $data_s['avatar']     = $img;
                $data_s['createtime'] = time();
                $user_id = Db::name('wxuser')->insertGetId($data_s);
            }
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['code' => -1, 'msg' => '修改失败' . $e->getMessage()]);
        }
        return $user_id;
    }


}
